package com.newsvoice.activity;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.rssreader.playtts.ShowExtractedArticle;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.TabHost;
import android.widget.Toast;

public class RecommendNewsActivity extends DashBoardActivity implements ICallbackHandler {
	private ListAdapter adapter;
	private String category = null;
	private ListView listView;
	private List<JSONObject> objects = null;
	private boolean reloadFlag = false;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.recommend_news_list_shows);
		listView = (ListView) findViewById(R.id.recommend_article_list);
        setHeader(getString(R.string.RecommendNewsActivityTitle), true, true, true, false);
		NewsVoiceApplication.getInstance();
		// adapter = this.getListAdapter();
		objects = (List<JSONObject>) NewsVoiceApplication.getAdaptersCache()
				.get("recommend");

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				JSONObject json = (JSONObject) adapter.getItem(arg2);
				try {
					URL url = (URL) json.get("link");
					// Intent browserIntent = new
					// Intent(Intent.ACTION_VIEW,
					// Uri.parse(url.toString()));
					// startActivity(browserIntent);
					Intent i1 = new Intent(getApplicationContext(),
							ShowExtractedArticle.class);
					i1.putExtra("urlString", url.toString());
					i1.putExtra("title", json.get("title").toString());
					startActivity(i1);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		});

		if (objects == null) {

			if (Util.isNetworkAvailable(this)) {
				loadRecommendNews();
				System.out.println("conneting internet");
			} else {
				Toast.makeText(getApplicationContext(), "no internet",
						Toast.LENGTH_SHORT).show();
			}
		} else {
			adapter = new RssListAdapter(this, objects);
			listView.setAdapter(adapter);
		}
	}

	@Override
	public void response(String response) {
		if (response.equals("error")) {
			Toast.makeText(getApplicationContext(), "fail connect to server",
					Toast.LENGTH_LONG).show();
		} else {
			Log.d("callMethod", response);
			/*
			 * try { JSONObject jso = new JSONObject(response); JSONArray ja =
			 * jso.getJSONArray("article"); List<Article> msg = new
			 * ArrayList<Article>(); for (int i = 0; i < ja.length(); i++) {
			 * Article m = new Article(); JSONObject jsonMsg =
			 * ja.getJSONObject(i);
			 * m.setArticleId(Long.valueOf(jsonMsg.getString("articleId")));
			 * m.setDescription(jsonMsg.getString("description"));
			 * m.setFeedId(Long.valueOf(jsonMsg.getString("feedId")));
			 * m.setImgLink(jsonMsg.getString("imgLink"));
			 * m.setPubDate(jsonMsg.getString("pubDate"));
			 * m.setTitle(jsonMsg.getString("title")); m.setUrl(new
			 * URL(jsonMsg.getString("url"))); msg.add(m); }
			 */
			objects = Util.convertToJSONObjects(response);
			adapter = new RssListAdapter(this, objects);

			listView.setAdapter(adapter);

			/*
			 * } catch (Exception e) { Log.d("Error: ", "Processing of " +
			 * response); if (e != null && e.getMessage() != null)
			 * Log.d("Error: ", e.getMessage()); else if (e != null)
			 * Log.d("Error: ", e.toString()); else Log.d("Error: ",
			 * "Null Exception"); }
			 */

		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		NewsVoiceApplication.getInstance();
		NewsVoiceApplication.getAdaptersCache().put("recommend", objects);
		System.out.println("onpause");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		System.out.println("ondestroy");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.recommend_news_show_option, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.recommend_reload_menu:
			if (Util.isNetworkAvailable(this)) {
				loadRecommendNews();
				System.out.println("conneting internet");
			} else {
				Toast.makeText(getApplicationContext(), "no internet",
						Toast.LENGTH_SHORT).show();
			}
			break;
		default:
			break;
		}

		return true;
	}

	private void loadRecommendNews() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(
				"idUser",
				this.getSharedPreferences(NewsVoiceApplication.filePrefrences,
						MODE_PRIVATE).getString("id", "noid"));
		callWebService(params);

	}

	private void callWebService(Map<String, String> params) {
		WebService webService = new WebService(
				"http://192.168.5.1:8080/VoiceNewsServer/rest/services/",
				"recommendarticles", params, this, WebService.GET_METHOD, this);
		webService.execute();
	}

}
